<template>
  <div class="category-manager-container">
    <!-- 搜索条件卡片 -->
    <el-card class="search-card" shadow="hover">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto" class="search-form">
        <el-form-item label="分类名称" prop="category_name">
          <el-input placeholder="请输入分类名称" v-model="queryParams.category_name" clearable style="width: 180px"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-select placeholder="全部" clearable v-model="queryParams.is_show" style="width: 100px">
            <el-option label="全部" value=""/>
            <el-option label="显示" :value="1"/>
            <el-option label="不显示" :value="0"/>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间" prop="add_date">
          <el-date-picker :editable="false" v-model="queryParams.add_date" type="daterange" range-separator="~"
                          start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" style="width: 300px"/>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="resetElement(queryFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域和数据表格卡片 -->
    <el-card class="table-card" shadow="hover">
      <div class="operation-header">
        <div class="operation-buttons">
          <el-button type="success" :icon="Plus" size="small" @click="addCategory">添加分类</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="delSelected">删除所选分类</el-button>
        </div>
        <div class="stats-info">
          共 <span class="highlight">{{ count }}</span> 条记录
        </div>
      </div>

      <!-- 数据展示表格 -->
      <el-table ref="elTableRef" :data="tableData" v-loading="loading" style="width: 100%" class="data-table">
        <!-- 复选框 -->
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="category_id" label="ID" width="120" align="center"/>
        <el-table-column label="分类名称" width="180" align="center">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>名称: {{ scope.row.category_name }}</div>
                <div>创建者: {{ scope.row.nickname }}</div>
              </template>
              <template #reference>
                <el-tag class="category-tag">{{ scope.row.category_name }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="intro" label="简介" min-width="250" show-overflow-tooltip/>
        <el-table-column label="显示状态" width="120" align="center">
          <template #default="{ row, $index }">
            <el-tag :type="row.is_show ? 'success' : 'info'" class="status-tag">
              {{ row.is_show ? '显示' : '不显示' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="100" align="center"/>
        <el-table-column prop="nickname" label="创建者" width="120" align="center"/>

        <el-table-column label="创建时间" width="180" align="center">
          <template #default="{row}">
            <div class="timestamp">
              {{ timestampFormat(row.add_date) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" min-width="140" align="center">
          <template #default=scope>
            <div class="action-buttons">
              <el-button link type="primary" size="small" @click="editHandler(scope.row.category_id)">修改</el-button>
              <el-button link type="danger" size="small" @click="deleteHandler(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          background
          v-model:current-page="page"
          @current-change="handleQuery"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        />
      </div>
    </el-card>

    <!-- 添加分类的弹框 -->
    <el-dialog v-model="isShowAddDialog" title="添加分类" width="600px">
      <el-form ref="addFormRef" :rules="addRules" :model="formData" label-width="100px" class="dialog-form">
        <el-form-item label="分类名称" prop="category_name">
          <el-input autocomplete="off" placeholder="请输入分类名称" v-model="formData.category_name"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="formData.is_show" active-text="显示" inactive-text="隐藏"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" controls-position="right"/>
        </el-form-item>

        <el-form-item label="发布者" prop="admin_id">
          <el-select placeholder="请选择发布者" v-model="formData.admin_id" style="width: 100%">
            <el-option label="请选择" :value="0"/>
            <el-option v-for="item in adminList" :key="item.admin_id" :label="item.nickname || item.username"
                       :value="item.admin_id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input v-model="formData.intro" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                    placeholder="请输入分类简介"/>
        </el-form-item>

        <el-form-item label="添加时间" prop="add_date">
          <el-date-picker type="datetime" :clearable="false" v-model="formData.add_date"
                          placeholder="选择添加日期" style="width: 100%"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetElement(addFormRef)">重置</el-button>
          <el-button @click="isShowAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm(addFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改分类的弹框 -->
    <el-dialog v-model="isShowEditDialog" title="修改分类" width="600px">
      <el-form ref="editFormRef" :rules="editRules" :model="editFormData" label-width="100px" class="dialog-form">
        <el-form-item label="分类名称" prop="category_name">
          <el-input autocomplete="off" placeholder="请输入分类名称" v-model="editFormData.category_name"/>
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="editFormData.is_show" active-text="显示" inactive-text="隐藏"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editFormData.sort" :min="0" :max="999" controls-position="right"/>
        </el-form-item>

        <el-form-item label="发布者" prop="admin_id">
          <el-select placeholder="请选择发布者" v-model="editFormData.admin_id" style="width: 100%">
            <el-option label="请选择" :value="0"/>
            <el-option v-for="item in adminList" :key="item.admin_id" :label="item.nickname || item.username"
                       :value="item.admin_id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input v-model="editFormData.intro" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                    placeholder="请输入分类简介"/>
        </el-form-item>

        <el-form-item label="添加时间" prop="add_date">
          <el-date-picker type="datetime" :clearable="false" v-model="editFormData.add_date"
                          placeholder="选择添加日期" style="width: 100%"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeFrom">取消</el-button>
          <el-button type="primary" @click="submitEditForm(editFormRef)">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import CategoryAPI, {type CategoryInfo} from "@/api/system/category.api";
import {formatUnix, timestampFormat} from "@/utils";
import {ElMessage, ElTable} from 'element-plus'
import moment from "moment";
import {Delete, Plus} from "@element-plus/icons-vue"
import type {FormInstance, FormRules} from 'element-plus';
import UserAPI, {type AdminInfo} from "@/api/system/user.api";
import { ref, reactive, onMounted, watch } from 'vue';

const page = ref(1)
const count = ref(0)
const pageSize = ref(10)
const tableData = ref<CategoryInfo[]>([])
const elTableRef = ref<InstanceType<typeof ElTable> | null>(null) // 绑定组件实例
const isShowAddDialog = ref<boolean>(false)
const isShowEditDialog = ref<boolean>(false)
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()
const adminList = ref<AdminInfo[]>([])
// 初始新增表单数据
const formData = ref<CategoryInfo>({
  category_name: '',
  sort: 0,
  is_show: true,
  intro: '',
  add_date: moment().format('YYYY-MM-DD HH:mm:ss'), // 或 new Date() 获取当前系统时间
  admin_id: 0
})
// 初始修改表单数据
const editFormData = ref<CategoryInfo>({
  category_name: '',
  sort: 0,
  is_show: true,
  intro: '',
  add_date: moment().format('YYYY-MM-DD HH:mm:ss'), // 或 new Date() 获取当前系统时间
  admin_id: 0
})
// 当前选中要修改的id
const currentCategoryId = ref<number>(0)

const queryParams = ref({category_name: '', is_show: '', start_date: '', end_date: "", add_date: ''})

const loading = ref(false)

onMounted(() => {
  fetchGetCategories()
})

watch(() => queryParams.value.add_date, (newVal) => {
  if (newVal && newVal.length === 2) {
    queryParams.value.start_date = formatUnix(newVal[0]) + ''
    queryParams.value.end_date = formatUnix(newVal[1]) + ''
  } else {
    queryParams.value.start_date = ''
    queryParams.value.end_date = ''
  }
})

// 自定义验证规则函数
const checkAdmin = (rule: any, value: any, callback: any) => {
  if (value === 0) {
    // 验证失败
    return callback(new Error('必须选择一个发布者'))
  }
  // 验证成功
  callback()
}

// 自定义验证修改表单函数
const checkUpdCategory = (rule: any, value: any, callback: any) => {
  if (currentCategoryId.value != 0) {
    CategoryAPI.checkUpdCategoryName(currentCategoryId.value, editFormData.value.category_name).then((data) => {
      console.log('data=>', data)
      callback() // 通过
    }).catch(err => {
      callback(new Error('编辑分类名重复，请更换一个' + err.message))
    })
  }
}

// 添加表单验证规则
const addRules = reactive<FormRules<CategoryInfo>>({
  category_name: [
    {required: true, message: '分类名不能为空', trigger: 'blur'},
    {min: 3, max: 16, message: '长度必须是3-16个字符', trigger: 'blur'},
    // 添加分类不需要检查重复名
  ],
  admin_id: [
    {validator: checkAdmin, trigger: 'blur'},
  ],
  intro: [
    {required: true, message: '简介不能为空', trigger: 'blur'},
  ]
})

// 编辑表单验证规则
const editRules = reactive<FormRules<CategoryInfo>>({
  category_name: [
    {required: true, message: '分类名不能为空', trigger: 'blur'},
    {min: 3, max: 16, message: '长度必须是3-16个字符', trigger: 'blur'},
    {validator: checkUpdCategory, trigger: 'blur'} // 只在编辑时检查
  ],
  admin_id: [
    {validator: checkAdmin, trigger: 'blur'},
  ],
  intro: [
    {required: true, message: '简介不能为空', trigger: 'blur'},
  ]
})

// 重置
const resetElement = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.resetFields(); // 等待表单重置完成
  fetchGetCategories(); // 再查询数据
}

// 新增提交表单
const submitAddForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 创建副本避免污染原始数据
        const submitData = {...formData.value}

        submitData.is_show = submitData.is_show ? 1 : 0;
        // 正确转换日期格式
        submitData.add_date = moment(submitData.add_date).unix().toString();

        await CategoryAPI.addSubmitCategory(submitData);

        ElMessage.success('添加分类成功');
        isShowAddDialog.value = false;
        fetchGetCategories();
      } catch (error) {
        console.error('添加失败:', error);
        ElMessage.error('添加分类失败');
      }
    }
  })
}

// 添加分类弹出表单
const addCategory = async () => {
  // 重置为干净的初始值
  formData.value = {
    category_name: '',
    sort: 0,
    is_show: true,
    intro: '',
    add_date: moment().format('YYYY-MM-DD HH:mm:ss'),
    admin_id: 0  // 重置为0（"请选择"状态）
  }

  // 重置验证状态
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }

  adminList.value = await UserAPI.getAdminList();
  isShowAddDialog.value = true;
}

// 获取表格初始数据
const fetchGetCategories = async () => {
  loading.value = true
  try {
    let result = await CategoryAPI.getCategoryInfo({
      page: page.value,
      pageSize: pageSize.value,
      ...queryParams.value
    })

    tableData.value = result.category
    count.value = result.count

  } catch (err) {
    console.log('获取分类数据失败:', err)
    ElMessage.error('获取分类列表失败')

  } finally {
    loading.value = false
  }
}

// 修改分类弹出表单
const editHandler = async (categoryId: number) => {
  // 获取管理员列表接口数据
  adminList.value = await UserAPI.getAdminList()
  // 修改当前选中category_id
  currentCategoryId.value = categoryId
  // 获取当前选中的Category
  // 获取完整响应
  const currentCategoryInfo = await CategoryAPI.getCategoryInfoById(currentCategoryId.value);
  currentCategoryInfo.add_date = timestampFormat(parseInt(currentCategoryInfo.add_date))
  // 从响应结构中提取数据
  if (currentCategoryInfo) {
    editFormData.value = {
      category_name: currentCategoryInfo.category_name,
      is_show: Boolean(currentCategoryInfo.is_show), // 确保转换为布尔值
      sort: currentCategoryInfo.sort,
      admin_id: currentCategoryInfo.admin_id,
      intro: currentCategoryInfo.intro, // 处理可能的空值
      add_date: currentCategoryInfo.add_date
    }

  }
  // 显示添加表单
  isShowEditDialog.value = true
}

// 修改提交表单
const submitEditForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      editFormData.value.is_show = editFormData.value.is_show ? 1 : 0
      editFormData.value.add_date = moment(editFormData.value.add_date).valueOf() / 1000 + ''
      editFormData.value.category_id = currentCategoryId.value

      console.log(editFormData.value)
      await CategoryAPI.editSubmitCategory(editFormData.value)

      ElMessage({
        type: 'success',
        message: '操作分类成功'
      })

      isShowEditDialog.value = false
      fetchGetCategories()
    } else {
      // 验证失败
      console.log('error submit!', fields)
    }
  })
}

// 关闭修改表单
const closeFrom = async () => {
  resetElement(editFormRef.value)
  isShowEditDialog.value = false
}

// 删除勾选的分类
const delSelected = async () => {
  if (!elTableRef.value) return
  // 获取选中的行
  const selectedRows = elTableRef.value.getSelectionRows()
  if (selectedRows.length === 0) {
    ElMessage({
      type: 'warning',
      message: '至少选择一条数据'
    })
    return
  }
  let ids = ''
  let idsArr: number[] = []
  selectedRows.forEach((item: CategoryInfo) => {
    if (item.category_id != null) {
      idsArr.push(item.category_id)
    }
  })
  ids = idsArr.join(',')
  // 发送请求删除多个
  await CategoryAPI.delBatchCategory(ids)
  ElMessage({
    type: 'success',
    message: '删除所选分类成功',
  })
  // 重新获取分页数据
  fetchGetCategories()
}

// 删除触发事件
const deleteHandler = (row: CategoryInfo) => {
  ElMessageBox.confirm(
    `你确认删除${row.category_name}吗`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
    if
    (row.category_id != null) {
      await CategoryAPI.deleteCategory(row.category_id)
    }
    fetchGetCategories()
    ElMessage(
      {type: "success", message: "删除成功"}
    )
  }).catch(() => {
    ElMessage(
      {type: "warning", message: "取消删除"}
    )
  })
}

// 搜索
const handleQuery = () => {
  fetchGetCategories()
}

// 每页显示数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchGetCategories()
}

</script>

<style scoped>
.category-manager-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.search-buttons {
  margin-left: auto;
}

.table-card {
  border-radius: 8px;
}

.operation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.stats-info {
  color: #606266;
  font-size: 14px;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
  margin: 0 4px;
}

.data-table {
  margin: 15px 0;
}

.data-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.category-tag {
  cursor: pointer;
  font-weight: 500;
}

.status-tag {
  padding: 5px 10px;
  border-radius: 12px;
}

.timestamp {
  color: #909399;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-form {
  padding: 0 20px;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding-top: 10px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .search-form {
    flex-direction: column;
  }

  .search-buttons {
    margin-left: 0;
    width: 100%;
    justify-content: flex-end;
  }

  .operation-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .stats-info {
    margin-top: 10px;
  }
}

@media (max-width: 768px) {
  .pagination-container {
    justify-content: center;
  }

  .data-table :deep(.el-table__cell) {
    padding: 8px 0;
  }

  .category-manager-container {
    padding: 15px;
  }
}

@media (max-width: 576px) {
  .operation-buttons {
    flex-wrap: wrap;
  }

  .dialog-form {
    padding: 0 10px;
  }
}
</style>
